#include "stdafx.h"
// SHARED_HANDLERS can be defined in an ATL project implementing preview, thumbnail
// and search filter handlers and allows sharing of document code with that project.
#ifndef SHARED_HANDLERS
#include "PagePro.h"
#endif

#include "PageProDoc.h"
#include "Configuration.h"
#include "MainFrm.h"
#include "PageProView.h"

#include <propkey.h>

#ifdef _DEBUG
#define new DEBUG_NEW
#endif

// CPageProDoc

IMPLEMENT_DYNCREATE(CPageProDoc, CDocument)

BEGIN_MESSAGE_MAP(CPageProDoc, CDocument)
	ON_COMMAND(ID_FILE_OPEN, &CPageProDoc::OnFileOpen) 
	ON_COMMAND(ID_FILE_CLOSE, &CPageProDoc::OnFileClose)	
END_MESSAGE_MAP()


/**
FreeImage error handler
@param fif Format / Plugin responsible for the error 
@param message Error message
*/
void FreeImageErrorHandler(FREE_IMAGE_FORMAT fif, const char *message) 
{
	CString Error_Message;
	
	Error_Message += FreeImage_GetFormatFromFIF(fif);
	
	Error_Message += " ";
	
	Error_Message += message;
	
	AfxMessageBox(Error_Message);
}
// CPageProDoc construction/destruction

CPageProDoc::CPageProDoc()
{
	 m_dib = NULL;
}

CPageProDoc::~CPageProDoc()
{
}

BOOL CPageProDoc::OnNewDocument()
{
	if (!CDocument::OnNewDocument())
		return FALSE;

	// TODO: add reinitialization code here
	// (SDI documents will reuse this document)

	return TRUE;
}




// CPageProDoc serialization

void CPageProDoc::Serialize(CArchive& ar)
{
	if (ar.IsStoring())
	{
		// TODO: add storing code here
	}
	else
	{
		// TODO: add loading code here
	}
}

#ifdef SHARED_HANDLERS

// Support for thumbnails
void CPageProDoc::OnDrawThumbnail(CDC& dc, LPRECT lprcBounds)
{
	// Modify this code to draw the document's data
	dc.FillSolidRect(lprcBounds, RGB(255, 255, 255));

	CString strText = _T("TODO: implement thumbnail drawing here");
	LOGFONT lf;

	CFont* pDefaultGUIFont = CFont::FromHandle((HFONT) GetStockObject(DEFAULT_GUI_FONT));
	pDefaultGUIFont->GetLogFont(&lf);
	lf.lfHeight = 36;

	CFont fontDraw;
	fontDraw.CreateFontIndirect(&lf);

	CFont* pOldFont = dc.SelectObject(&fontDraw);
	dc.DrawText(strText, lprcBounds, DT_CENTER | DT_WORDBREAK);
	dc.SelectObject(pOldFont);
}

// Support for Search Handlers
void CPageProDoc::InitializeSearchContent()
{
	CString strSearchContent;
	// Set search contents from document's data. 
	// The content parts should be separated by ";"

	// For example:  strSearchContent = _T("point;rectangle;circle;ole object;");
	SetSearchContent(strSearchContent);
}

void CPageProDoc::SetSearchContent(const CString& value)
{
	if (value.IsEmpty())
	{
		RemoveChunk(PKEY_Search_Contents.fmtid, PKEY_Search_Contents.pid);
	}
	else
	{
		CMFCFilterChunkValueImpl *pChunk = NULL;
		ATLTRY(pChunk = new CMFCFilterChunkValueImpl);
		if (pChunk != NULL)
		{
			pChunk->SetTextValue(PKEY_Search_Contents, value, CHUNK_TEXT);
			SetChunkValue(pChunk);
		}
	}
}

#endif // SHARED_HANDLERS

// CPageProDoc diagnostics

#ifdef _DEBUG
void CPageProDoc::AssertValid() const
{
	CDocument::AssertValid();
}

void CPageProDoc::Dump(CDumpContext& dc) const
{
	CDocument::Dump(dc);
}
#endif //_DEBUG

// CPageProDoc commands
/////////////////////////////////////////////////////////////////////
BOOL CPageProDoc::OpenBatch(BOOL loadThumbnailCtrl)
{		
	CMainFrame*	pMainFrame =  (CMainFrame*)(AfxGetApp()->m_pMainWnd);
	ASSERT_VALID(pMainFrame);
	pMainFrame->WriteBatchInfo(this->m_batch);

	FIBITMAP* temp_dib =this->m_batch.GetFrame();
	
	if (temp_dib == NULL) 
	{		
		return FALSE;
	}
	if (m_dib)
	{
		OnFileClose(); // if a previous file is open - close it
	}

	m_dib = temp_dib;

	////  MSDN article Q108587 HOWTO: Get Current CDocument or CScrollView from Anywhere
	CPageProView* pView = (CPageProView*)pMainFrame->GetActiveView();		
	ASSERT_VALID(pView);


	return TRUE;
}
/////////////////////////////////////////////////////////////////////
void CPageProDoc::OnFileOpen()
{
	FreeImage_SetOutputMessage(FreeImageErrorHandler);

	TCHAR strFilter[] = {TEXT(GRAPH_FILES_FILTER)};		
	CString FileName;
	CFileDialog dlg(TRUE, NULL, NULL, 0, strFilter);
	
	if( dlg.DoModal() == IDOK )		
		FileName = dlg.GetPathName();
	else return;
	if(this->m_batch.GetID() != GUID_NULL)
	{
		CBatch m_newBatch ;
		this->m_batch =m_newBatch;
		m_newBatch.~CBatch();
	}
	this->m_batch.Init(FileName);	
	this->m_batch.FileLoad();
 	int _pageCount =this->m_batch.GetPageCount();
	OpenBatch(TRUE);

	CMainFrame* pMainFrame = static_cast<CMainFrame*>((AfxGetApp()->m_pMainWnd)->GetRoutingFrame_());
	HTREEITEM  m_hBatchItem = pMainFrame->AddBatch(this->m_batch);
		
	// Add the filename to the MRU list manually - since we changed the default OnCommand routing
	AfxGetApp()->AddToRecentFileList(FileName.GetBuffer(FileName.GetLength()));	

	for(int index=0 ;  index< _pageCount  ; index++)
	{
		pMainFrame->AddPage(m_hBatchItem,index);
	}
}
/////////////////////////////////////////////////////////////////////
void CPageProDoc::OnFileClose() 
{
	CPageProView* pView = (CPageProView*)((CMainFrame*)(AfxGetApp()->m_pMainWnd))->GetActiveView();	
	ASSERT_VALID(pView);
	
	// free the loaded FIBITMAP
	if(m_dib)
	{
		FreeImage_Unload(m_dib);
	}		
	m_dib = NULL;
		
	//pView->ResetScrollSizes();
	//if(m_pThread)
	//{
	//	m_pThread->CanKillThread();
	//	delete m_pThread; // calls the destructor and closes the thread
	//}
	UpdateAllViews (NULL);	
}